﻿#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace octalforty.Chinchillin.Actions.Sync
{
    /// <summary>
    /// Represents a Synchronization Manager, which can perform various item-independent synchronization tasks.
    /// </summary>
    /// <typeparam name="TIdentity"></typeparam>
    /// <typeparam name="TChecksum"></typeparam>
    public class SyncManager<TIdentity, TChecksum>
        where TIdentity : IEquatable<TIdentity>
        where TChecksum : IEquatable<TChecksum>
    {
        #region Private Fields
        private readonly ISyncCallback<TIdentity, TChecksum> syncCallback;
        private readonly object context;
        private readonly IEqualityComparer<SyncItem<TIdentity, TChecksum>> equalityComparer;
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="SyncManager{TIdentity,TChecksum}"/> class with provided <paramref name="syncCallback"/>
        /// and <paramref name="context"/>.
        /// </summary>
        /// <param name="syncCallback"></param>
        /// <param name="context"></param>
        public SyncManager(ISyncCallback<TIdentity, TChecksum> syncCallback, object context)
        {
            if(syncCallback == null) throw new ArgumentNullException("syncCallback");

            this.syncCallback = syncCallback;
            this.context = context;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SyncManager{TIdentity,TChecksum}"/> class with provided <paramref name="syncCallback"/>, 
        /// <paramref name="context"/> and <paramref name="equalityComparer"/>.
        /// </summary>
        /// <param name="syncCallback"></param>
        /// <param name="context"></param>
        /// <param name="equalityComparer"></param>
        public SyncManager(ISyncCallback<TIdentity, TChecksum> syncCallback, object context, 
            IEqualityComparer<SyncItem<TIdentity, TChecksum>> equalityComparer) :
            this(syncCallback, context)
        {
            if(equalityComparer == null) throw new ArgumentNullException("equalityComparer");

            this.equalityComparer = equalityComparer;
        }

        /// <summary>
        /// Performs one-way synchronization by applying modifications required for items in <paramref name="target"/>
        /// to be identical to items in <paramref name="source"/>.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public SyncResult SyncOneWay(ICollection<SyncItem<TIdentity, TChecksum>> source, ICollection<SyncItem<TIdentity, TChecksum>> target)
        {
            if(source == null) throw new ArgumentNullException("source");
            if(target == null) throw new ArgumentNullException("target");

            return SyncOneWayInternal(source, target);
        }

        private SyncResult SyncOneWayInternal(IEnumerable<SyncItem<TIdentity, TChecksum>> source, IEnumerable<SyncItem<TIdentity, TChecksum>> target)
        {
            var syncContext = new SyncContext(context);

            var skipped = 0;
            var deleted = 0;
            var synced = 0;

            //
            // First, we filter only identical elements
            var identical = GetIdenticalItems(source, target);

            foreach(var item in identical)
            {
                syncCallback.SkipLocalItem(syncContext, item);
                skipped++;
            } // foreach

            //
            // Next, delete remaining items from target
            foreach(var item in GetItemsForDeletion(target, identical))
            {
                syncCallback.DeleteLocalItem(syncContext, item);
                deleted++;
            } // foreach

            //
            // And finally, sync missing items
            foreach(var item in GetItemsForSyncing(source, identical))
            {
                syncCallback.SyncRemoteItem(syncContext, item);
                synced++;
            } // foreach

            return new SyncResult(skipped, deleted, synced);
        }

        private IEnumerable<SyncItem<TIdentity, TChecksum>> GetItemsForSyncing(IEnumerable<SyncItem<TIdentity, TChecksum>> source, IEnumerable<SyncItem<TIdentity, TChecksum>> identical)
        {
            return equalityComparer == null ? source.Except(identical) : source.Except(identical, equalityComparer);
        }

        private IEnumerable<SyncItem<TIdentity, TChecksum>> GetItemsForDeletion(IEnumerable<SyncItem<TIdentity, TChecksum>> target, IEnumerable<SyncItem<TIdentity, TChecksum>> identical)
        {
            return equalityComparer == null ? target.Except(identical) : target.Except(identical, equalityComparer);
        }

        private IEnumerable<SyncItem<TIdentity, TChecksum>> GetIdenticalItems(IEnumerable<SyncItem<TIdentity, TChecksum>> source, IEnumerable<SyncItem<TIdentity, TChecksum>> target)
        {
            return equalityComparer == null ? 
                source.Intersect(target) :
                source.Intersect(target, equalityComparer);
        }
    }
}